
name,reader_port,connect_to = ...
local socket = require'socket'
serialize = require'serialize'
ev = require't3'
assert(reader_port)
reader_port = tonumber(reader_port)
--print("reader_port",reader_port)
local reader_conn,err = socket.connect('localhost',reader_port)

reader_conn:settimeout(0)
tab_contacts = {}

local function timer ()
  --if not connect_to then
    --print'timer'
  --end
  local str = reader_conn:receive()
  if str then
    for k,v in pairs(tab_contacts) do
      --print(k,v)
      ev.send(v,"if not tab_contacts."..name.." then tab_contacts."..name.." = '"..ev.id().."'"..
                " print'connected to "..name.."' end".. 
                " print('" .. name ..":"..str.."')")
    end
  end 
end

function update_contacts (tab)
  for k,v in pairs(tab) do
    if k~= ev.id() then
      tab_contacts[k]=v
    end
  end
end

ev.set_timer(0.5, timer)

local init
if connect_to then
  init = function ()
    local str = "print'connected to "..name.." in "..ev.id().."' "..
    "tab_contacts."..name.." = '"..ev.id().."' "..
    "ev.send('"..ev.id().."',[[tab_contacts[']]..name..[[']=']]..ev.id().. [[' print'connected to ]]..name ..[[' ]]..serialize('local tab',tab_contacts).. [[ update_contacts(tab)]])"
    ev.send(connect_to,str)
  end
end

ev.loop(init)

